import { PageDto } from "../../../models/page.model";
import { UaIpEntity } from "../../../models/ua-ip.model";
import { UaUserDeckEntity, UaUserDeckSearchDto } from "../../../models/ua-user-deck.model";
import { GlobalService } from "../../../services/global.service";
import { LocalStorage } from "../../../services/local-storage.service";
import { UaIpService } from "../../../services/ua-ip.service";
import { UserDeckService } from "../../../services/ua-user-deck.service";
import { formatTime } from "../../../utils/util";

// pages/user/user-deck-list/user-deck-list.page.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    FILE_HOST: GlobalService.STATIC_ASSETS_HOST,
    CDN_HOST: GlobalService.FILE_HOST,
    ipList: [] as { label: string, value: number }[],
    ipLogoMap: {} as { [key: number]: string },
    deckList: [] as UaUserDeckEntity[],
    pickerVisible: false,
    pickerValue: undefined,
    tags: [] as string[],
    tagList: [{ label: "全部分组", value: "" }, { label: "默认分组", value: '默认分组' }],
    tagText: '全部分组',
    tag: '',
    tagVisible: false,
    fab: {
      theme: 'danger'
    },
    battleDeckId: 0
  },

  customData: {
    page: 1,
    totalPage: 1,
    searchRequest: {} as UaUserDeckSearchDto
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options: any) {
    wx.setNavigationBarTitle({
      title: '我的卡组'
    });
    if (!!options.deckId) {
      this.setData({
        battleDeckId: +options.deckId
      })
    }
    UaIpService.fetchUaIpList().then((response: UaIpEntity[]) => {
      const ipList: { label: string, value: number }[] = [];
      const ipLogoMap: { [key: number]: string } = {};
      for (const ip of response.reverse()) {
        ipList.push({
          label: ip.ipTitleCn!,
          value: ip.id!
        });
        ipLogoMap[ip.id!] = ip.ipTitleLogo!;
      }
      this.setData({
        ipList,
        ipLogoMap,
      });
      this.load();
    });
  },

  initTags() {
    UserDeckService.getTags().then((response: string[]) => {
      if (response) {
        const tags = response;
        const tagList = [{ label: "全部分组", value: "" }, { label: "默认分组", value: '默认分组' }];
        for (const tag of tags) {
          tagList.push({
            label: tag, value: tag
          })
        }
        this.setData({ tagList, tags });
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.customData.page = 1;
    this.load();
    this.initTags();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.customData.page = 1;
    this.load();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.customData.page + 1 > this.customData.totalPage) {
      return;
    }
    this.customData.page++;
    this.load();
  },

  load() {
    const search = { userId: LocalStorage.getUserInfo()?.id };
    Object.assign(search, this.customData.searchRequest)
    UserDeckService.searchWithPage(search, this.customData.page).then((response: PageDto<UaUserDeckEntity>) => {
      this.customData.totalPage = response.meta!.pageCount!;
      for (const item of response.data ?? []) {
        const date = new Date(item.updateDate ?? Date.now());
        if (!!item.cover) {
          item.coverCardList = item.cover.split(';');
        } else {
          item.coverCardList = [];
        }
        item.updateDateStr = formatTime(date);
        if (item.mainEnergyType) {
          item.mainEnergyTypeLogo = `/jp/images/cardlist/icon/resource/ico_resource_energy_${item.mainEnergyType?.toLowerCase()}1.png`;
        }
      }
      if (this.customData.page === 1) {
        this.setData({
          deckList: response.data
        })
      } else {
        this.setData({
          deckList: [...this.data.deckList, ...response.data!]
        })
      }
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  onChoose(e: any) {
    if (!!this.data.battleDeckId) {
      wx.navigateTo({
        url: `/pages/user/deck-battle-test/deck-battle-test.page?deckId1=${this.data.battleDeckId}&deckId2=${e.currentTarget.dataset['id']}`,
      });
    } else {
      wx.navigateTo({
        url: `/pages/user/user-deck-detail/user-deck-detail.page?ipId=${e.currentTarget.dataset['ipid']}&deckId=${e.currentTarget.dataset['id']}`,
      });
    }
  },

  onDelete(e: any) {
    const index = e.currentTarget.dataset.index;
    const deck = this.data.deckList[index];
    wx.showModal({
      title: '是否删除？',
      confirmText: "删除",
      cancelText: "取消",
      showCancel: true,
      confirmColor: "#eb445a",
      success: (res) => {
        if (res.confirm) {
          this.removeDeck(deck);
        }
      }
    });
  },

  removeDeck(deck: UaUserDeckEntity) {
    UserDeckService.removeById(deck.id!).then(() => {
      this.onShow();
    })
  },

  chooseIp() {
    this.setData({
      pickerVisible: true
    })
  },

  onPickerChange(e: any) {
    const { value } = e.detail;
    wx.navigateTo({
      url: `/pages/user/user-deck-add/user-deck-add.page?ipId=${value}`,
    });
  },

  onPickerCancel() {
    this.setData({
      pickerVisible: false
    });
  },


  filter() {
    this.setData({
      popupVisible: true
    })
  },

  onPopupVisibleChange(e: any) {
    this.setData({
      popupVisible: e.detail.visible
    });
  },

  onReset(e: any) {
    this.customData.searchRequest = e.detail;
    this.setData({
      tag: '',
      tagText: "全部分组"
    });
  },

  onSearch(e: any) {
    console.log(e)
    this.customData.searchRequest = e.detail;
    let tag = '';
    let tagText = '';
    if (this.customData.searchRequest.tag === '') {
      tag = "默认分组";
      tagText = "默认分组";
    } else if (this.customData.searchRequest.tag === undefined) {
      tag = "";
      tagText = "全部分组";
    } else {
      tag = this.customData.searchRequest.tag;
      tagText = this.customData.searchRequest.tag;
    } this.setData({
      tag,
      tagText,
      popupVisible: false
    });
    this.onPullDownRefresh();
  },


  onTagPicker() {
    this.setData({
      tagVisible: true
    });
  },

  onTagPickerCancel() {
    this.setData({
      tagVisible: false
    });
  },

  onTagPickerConfirm(e: any) {
    this.setData({
      tagText: e.detail.label[0],
      tag: e.detail.value[0],
      tagVisible: false
    });
    let tag: string | undefined = undefined;
    if (this.data.tag !== '') {
      tag = this.data.tag === '默认分组' ? '' : this.data.tag
    }
    this.customData.searchRequest.tag = tag;
    this.onPullDownRefresh();
  },
})